﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel.Composition;
using SoundEdge.Media.Wave;
using SoundEdge.Media.Settings;

namespace SoundEdge.Media.Wave.Plugins
{
    [Export(typeof(IOutputDevicePlugin))]
    public class WaveOutPlugin : IOutputDevicePlugin
    {
        private WaveOutSettings _settings;
        public IOutputSettings Settings
        {
            get { return _settings; }
        }

        public WaveOutPlugin()
        {
            _settings = WaveOutSettings.LoadSettings<WaveOutSettings>("settings.xml");
            if (_settings == null)
            {
                _settings = new WaveOutSettings();
            }
        }

        public IWavePlayer CreateDevice()
        {
            IWavePlayer device;
            WaveCallbackStrategy strategy = _settings.CallbackStrategy;
            if (strategy == WaveCallbackStrategy.Event)
            {
                var waveOut = new WaveOutEvent();
                waveOut.DeviceNumber = _settings.DeviceNumber;
                waveOut.DesiredLatency = _settings.Latency;
                device = waveOut;
            }
            else
            {
                WaveCallbackInfo callbackInfo = strategy == WaveCallbackStrategy.NewWindow ? WaveCallbackInfo.NewWindow() : WaveCallbackInfo.FunctionCallback();
                WaveOut outputDevice = new WaveOut(callbackInfo);
                outputDevice.DeviceNumber = _settings.DeviceNumber;
                outputDevice.DesiredLatency = _settings.Latency;
                device = outputDevice;
            }
            // TODO: configurable number of buffers

            return device;
        }

        public virtual UserControl CreateSettingsPanel()
        {
            throw new NotSupportedException();
        }

        public string Name
        {
            get { return "WaveOut"; }
        }

        public bool IsAvailable
        {
            get { return WaveOut.DeviceCount > 0; }
        }

        public int Priority
        {
            get { return 1; } 
        }
    }
}
